﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Frogism.Core;
using System.Data.SqlClient;
using System.Data;

namespace Frogism.Data {
  public abstract class LoaderUpdateBase<T, I> : LoaderBase<T, I>
    where T : ObjectIdBase
    where I : IObjectIdBase {
    public virtual I CreateAndGet(I obj) {
      using (SqlConnection conn = GetConnection()) {
        SqlCommand cmd = conn.CreateCommand();
        cmd.CommandText = ProcNameCreate;
        cmd.CommandType = CommandType.StoredProcedure;
        FillParameters(cmd, obj);
        SqlParameter pOut = cmd.CreateParameter();
        pOut.ParameterName = "@newId";
        pOut.Direction = ParameterDirection.Output;
        pOut.SqlDbType = SqlDbType.Int;
        cmd.Parameters.Add(pOut);
        cmd.ExecuteNonQuery();

        return base.GetById((int)pOut.Value);
      }
    }
    public virtual void Create(I obj) {
      using (SqlConnection conn = GetConnection()) {
        SqlCommand cmd = conn.CreateCommand();
        cmd.CommandText = ProcNameCreate;
        cmd.CommandType = CommandType.StoredProcedure;
        FillParameters(cmd, obj);
        cmd.ExecuteNonQuery();
      }
    }
    public void Save(I obj) {
      using (SqlConnection conn = GetConnection()) {
        SqlCommand cmd = conn.CreateCommand();
        cmd.CommandText = ProcNameSave;
        cmd.CommandType = CommandType.StoredProcedure;
        AddIntParam(cmd, "Id", obj.Id);
        FillParameters(cmd, obj);
        cmd.ExecuteNonQuery();
      }
    }
    public void Delete(int id) {
      this.ProcedureNonQuery(ProcNameDelete, id);
    }
    protected abstract void FillParameters(SqlCommand cmd, I Obj);
    protected abstract string ProcNameSave { get; }
    protected abstract string ProcNameCreate { get; }
    protected abstract string ProcNameDelete { get; }
  }
}
